package com.mall.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.mall.common.Const;
import com.mall.common.ResponseCode;
import com.mall.common.ServerResponse;
import com.mall.dao.MmallCategoryMapper;
import com.mall.dao.MmallProductMapper;
import com.mall.pojo.MmallCategory;
import com.mall.pojo.MmallProduct;
import com.mall.pojo.MmallProductWithBLOBs;
import com.mall.service.ICategoryService;
import com.mall.service.IProductService;
import com.mall.util.DatetimeUtil;
import com.mall.util.PropertiesUtil;
import com.mall.vo.ProductDetailVo;
import com.mall.vo.ProductListVo;

@Service
public class productServiceImpl implements IProductService {
	
	@Autowired
	private MmallProductMapper productMapper;
	
	@Autowired
	private MmallCategoryMapper categoryMapper;
	
	@Autowired
	private ICategoryService categoryService;
	
	@Override
	public ServerResponse<String> addorUpdateProduct(MmallProductWithBLOBs product) {
		
		if(product != null){
			
			//如果商品的sub_images不为空,取sub_images的第一个为main_image
			if(StringUtils.isNotBlank(product.getSubImages())){
				String[] array = product.getSubImages().split(",");
				product.setMainImage(array[0]);
			}
			
			//id不为空说明是更新产品
			if(product.getId()!= null){
				int count = productMapper.updateByPrimaryKeyWithBLOBs(product);
				if(count > 0 ){
					return ServerResponse.createBySuccess("更新商品成功");
				}else{
					return ServerResponse.createByErrorMessage("更新商品失败");
				}
			}else{
				//说明是新增产品
				int count = productMapper.insert(product);
				if(count > 0 ){
					return ServerResponse.createBySuccess("新增商品成功");
				}else{
					return  ServerResponse.createByErrorMessage("更新商品失败");
				}
			}
		
		}
		return ServerResponse.createByErrorMessage("新增或更新商品参数不正确");
	}

	@Override
	public ServerResponse<String> setProductStatus(Integer productId, Integer status) {
		
		if(productId == null || status == null){
			return ServerResponse.createByErroerCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
		}
		
		MmallProductWithBLOBs record = new MmallProductWithBLOBs();
		record.setId(productId);
		record.setStatus(status);
		int count = productMapper.updateStatusByProductId(record );
		if(count ==0){
			return ServerResponse.createByErrorMessage("修改商品状态失败");
		}
		return ServerResponse.createBySuccess("修改商品状态成功");
	}

	@Override
	public ServerResponse<ProductDetailVo> getDeatil(Integer productId) {
		if(productId == null){
			return ServerResponse.createByErroerCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
		}
		
		MmallProductWithBLOBs product = productMapper.selectByPrimaryKey(productId);
		
		if(product == null){
			return ServerResponse.createByErrorMessage("商品已下架或者删除");
		}
		ProductDetailVo productVo = getDetailVo(product);
		
		return ServerResponse.createBySuccess(productVo);
	}
	
	//得到ProductDetailVo对象
	private ProductDetailVo getDetailVo(MmallProductWithBLOBs product){
		
		ProductDetailVo vo = new ProductDetailVo();
		
		vo.setId(product.getId());
		vo.setCategoryId(product.getCategoryId());
		vo.setName(product.getName());
		vo.setSubtitle(product.getSubtitle());
		vo.setMainImage(product.getMainImage());
		vo.setSubImages(product.getSubImages());
		vo.setDetail(product.getDetail());
		vo.setPrice(product.getPrice());
		vo.setStock(product.getStock());
		vo.setStatus(product.getStatus());
		
		vo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "ftp://192.168.1.106/img/"));
		
		vo.setUpdateTime(DatetimeUtil.dateToStr(product.getUpdateTime()));
		vo.setCreateTime(DatetimeUtil.dateToStr(product.getCreateTime()));
		
		MmallCategory category = categoryMapper.selectByPrimaryKey(product.getCategoryId());
		if(category == null){
			vo.setParentCategoryId(0);   //默认根节点
		}else{
			vo.setParentCategoryId(category.getParentId());
		}
		
		return vo;
	}

	@Override
	public ServerResponse<PageInfo> getList(int pageNum, int pageSize) {
		
		//分页
		PageHelper.startPage(pageNum, pageSize);
		
		List<MmallProduct> products = productMapper.selectList();
		
		List<ProductListVo> volists = new ArrayList<>();
		
		for (MmallProduct product : products) {
			ProductListVo vo = getListVo(product);
			volists.add(vo);
		}
		
		PageInfo info = new PageInfo(products);
		info.setList(volists);
		
		return ServerResponse.createBySuccess(info);
		
	}
	
	// 将从数据库中查询出来的对象转为我们需要的对象
	private ProductListVo getListVo(MmallProduct product){
		
		ProductListVo vo = new ProductListVo();
		vo.setId(product.getId());
		vo.setCategoryId(product.getCategoryId());
		vo.setName(product.getName());
		vo.setStatus(product.getStatus());
		vo.setMainImage(product.getMainImage());
		vo.setPrice(product.getPrice());
		vo.setSubtitle(product.getSubtitle());
		vo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "http://img.happymall.com/"));
		
		return vo;
	}
	
	@Override
	public ServerResponse<PageInfo> searchProduct(String productName, Integer productId,int pageNum, int pageSize){
		
		//分页
		PageHelper.startPage(pageNum, pageSize);
		
		//若商品名不为空,将名字转为 %name% 的形式.
		if(StringUtils.isNotBlank(productName)){
			productName = new StringBuilder().append("%").append(productName).append("%").toString();
		}
		//查询
		List<MmallProduct> products = productMapper.selectProductByProductIdOrName(productName, productId);
		
		List<ProductListVo> volist = new ArrayList<>();
		for (MmallProduct product : products) {
			ProductListVo provo = getListVo(product);
			volist.add(provo);
		}
		
		PageInfo info = new PageInfo(products);
		info.setList(volist);
		
		return ServerResponse.createBySuccess(info);
	}

	@Override
	public ServerResponse getProductDetail(Integer productId) {
		if(productId == null){
			return ServerResponse.createByErroerCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), "参数错误");
		}
		MmallProductWithBLOBs product = productMapper.selectByPrimaryKey(productId);
		if(product == null ){
			return ServerResponse.createByErrorMessage("商品已下架或者删除");
		}
		
		//前台的产品搜索与后台的不同之处就是要在这判断产品的状态
		//1为在售状态
		if(product.getStatus() != Const.STATUS.ON_SALE.getStatus()){
			return ServerResponse.createByErrorMessage("商品已下架或者删除");
		} 
		
		ProductDetailVo productVo = getDetailVo(product);
		return ServerResponse.createBySuccess(productVo);
	}

	@Override	//前台产品搜索及动态排序
	public ServerResponse getProductList(String keyword, Integer categoryId, int pageNum, int pageSize,
			String orderBy) {
		
		//若关键字和分类id都没有传过来,报错
		if(StringUtils.isBlank(keyword) && categoryId == null){
			return ServerResponse.createByErroerCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),"参数不正确");
		}
		
		//若关键字不为空,拼接成 %keyname% 的形式.
		if(StringUtils.isNotBlank(keyword)){
			keyword = new StringBuffer().append("%").append(keyword).append("%").toString();
		}
		
		List<Integer> categoryIdList = new ArrayList<Integer>();
		
		//如果id不为空
		if(categoryId != null){
			MmallCategory category = categoryMapper.selectByPrimaryKey(categoryId);
			
			if(category == null && StringUtils.isBlank(keyword)){
				//没有该分类而且还没有关键字,这个时候返回一个空的结果集,不报错
				PageHelper.startPage(pageNum, pageSize);
				List list = new ArrayList();
				PageInfo info = new PageInfo(list );
				
				return ServerResponse.createBySuccess(info);
			}
			
			//有该分类,查出该分类及所有子分类的id
			categoryIdList = categoryService.getDeepCategory(category.getId()).getData();
		}
		
		//分页
		PageHelper.startPage(pageNum, pageSize);
		
		//排序处理
		if(StringUtils.isNotBlank(orderBy)){
			if(Const.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)){
				String[] str = orderBy.split("_");
				String result = str[0] + " " +str[1];
				//排序规则: price desc/asc
				PageHelper.orderBy(result); 
			}
		}
		
		//查询
		List<MmallProduct> products = productMapper.selectByNameAndCategoryIds(keyword,categoryIdList);
		
		List<ProductListVo> productVoList = new ArrayList<>();
		
		for (MmallProduct product : products) {
			ProductListVo vo = getListVo(product);
			productVoList.add(vo);
		}
		
		//取分页结果,并将集合替换成组装后的对象
		PageInfo info = new PageInfo(products);
		info.setList(productVoList);
		
		return ServerResponse.createBySuccess(info);
	}
	
}
